<?php
class Redirect_model extends Model {
	function Redirect_model()
	{
		parent::Model();
	}
	
	public function store_redirect($location = '/')
	{
		// if the redirect token doesn't already exist, create it
		$hash = md5($location);
		if (!$this->load_redirect($location))
		{
			// try to discover the referring bricabox's id, if any
			$_parts = parse_url($location);
			$_host 	= $_parts['host'];
			preg_match('/^([_a-z0-9]+)\./', $_host, $matches);
			$_sub	= $matches[1];
			
			$bricabox_query = $this->db->query("select id from bricaboxes
				where
					(use_custom_domain = 0 and subdomain = ?)
					or
					(use_custom_domain = 1 and custom_domain = ?)
				limit 1",
					array(
						$_sub,
						$_host
					));
			$_bricabox_id = -1;
			if ($bricabox_query->num_rows() == 1)
				$_bricabox_id = $bricabox_query->first_row()->id;
			$this->db->query('insert into redirects (created_at,token,url,bricabox_id) values(NOW(), ?, ?, ?)', array($hash, $location, $_bricabox_id));
		}
		return $hash;
	}
	
	public function load_redirect($location)
	{
		return $this->load_redirect_by_token(md5($location));
	}
	
	public function load_redirect_by_token($token)
	{
		$loc = $this->db->query('select * from redirects where token = ?', $token);
		if ($loc->num_rows())
		{
			return $loc->first_row();
		}
	}
	
	public function redirect_to($token, $ignore_login_success = false, $login = "", $pass = "")
	{
		$token = $this->load_redirect_by_token($token);
		if ($ignore_login_success)
		{
			if ($token)
				$r = $token->url;
		}
		else
		{
			// custom domain, so redirect back to the login_success url first
			$parsed = parse_url($token->url);
			$port	= ($parsed['port'] == 80 || $parsed['port'] == 443) ? '' : ":{$parsed['port']}";
			$r		= "{$parsed['scheme']}://{$parsed['host']}{$port}/account/login_success/{$token->token}/{$login}/{$pass}";
		}
		header("Location: {$r}");
	}
}
?>